var map;
var geocoder = new google.maps.Geocoder();
var directionsService = new google.maps.DirectionsService();

var customersArray = []; 	//array of all customers - input
var distancesArray = [];	//array of pairs of distance - calculate
var routesArray = [];		//array of pairs of routes - calculate

var directionsRenderersArray = []; //array of directionsRenderers

function setDepot(address) {
	if (address == '') {
		alert("Please input address as a non empty string.");
		return;
	}
	
	geocoder.geocode({ 'address': address }, function (results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
			var latLng = results[0].geometry.location;
			var marker = new google.maps.Marker({
				position: latLng,
				title: 'Depot: ' + address,
				animation: google.maps.Animation.DROP,
				map: map
			});
			customersArray[0]._marker.setMap(null);
			customersArray[0] = new Customer(address, 0, latLng, marker);
		}
		else {
			alert('The input address is invalid. Please enter again.');
		}
	});
}

function inputCustomer(address, demand) {
	if (address == '') {
		alert("Please input address as a non empty string.");
		return;
	}
	if (isNaN(demand) || demand <= 0) {
		alert("Please input demand as a positive number.");
		return;
	}
	var address_existed = false;
	for (var i in customersArray) {
		if (customersArray[i]._address == address) {
			address_existed = true;
			break;
		}
	}
	if (address_existed) {
		alert("This address has already been input. Please add a different address.");
		return;
	}
	
	geocoder.geocode({ 'address': address }, function (results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
		
			var latLng = results[0].geometry.location;
			var marker = new google.maps.Marker({
				position: latLng,
				title: address,
				animation: google.maps.Animation.DROP,
				map: map
			});
			customersArray.push(new Customer(address, demand, latLng, marker));
			
			$('#table_addresses #tr_addressinput').before(''+
				'<tr class="tr_address">'+
					'<td style="width: 55%;">' + address + '</td>'+
					'<td style="width: 25%;">' + demand + '</td>'+
					'<td style="width: 20%; text-align: center;"><span class="button_delete button bgred">Del</span></td>'+
				'</tr>'
			);
			
			$('.button_delete').unbind().click(function(){
				var i;
				var address_to_delete = $(this).parent().prev().html();
				for (i in customersArray) {
					if (customersArray[i]._address == address_to_delete) {
						break;
					}
				}
				customersArray[i]._marker.setMap(null);
				customersArray.splice(i,1);
				$(this).parents('tr .tr_address').remove();
			});
			
		}
		else {
			alert('The input address is invalid. Please enter again.');
		}
	});

}

function calcDistances() { //fill up distancesArray and routesArray
	var count = customersArray.length * customersArray.length;
	for (var i = 0; i < customersArray.length; i++) {
		distancesArray[i] = [];
		routesArray[i] = [];
		for (var j = 0; j < customersArray.length; j++) {
			distancesArray[i][j] = -1;
			routesArray[i][j] = null;
			if (i!=j) {
				var request = {
					origin: customersArray[i]._latLng, 
					destination: customersArray[j]._latLng,
					// waypoints: [
						// {
							// location: "...",
							// stopover: true
						// }
					// ],
					// optimizeWaypoints: true,
					travelMode: google.maps.DirectionsTravelMode.DRIVING
				};
				(function(i,j){
					directionsService.route(request, function(result, status) {
						if (status == google.maps.DirectionsStatus.OK) {
							distancesArray[i][j] = parseInt(result.routes[0].legs[0].distance.value);
							routesArray[i][j] = result;
							count--;
						}
					});
				})(i,j);
			} else {
				count--;
			}
		}
	}
	var checkFinished = setInterval(function(){
		if (count == 0) {
			clearInterval(checkFinished);
			alert('Finished calculating distances.');
		}
	},500);
}


$(document).ready(function(){
	map = new google.maps.Map(document.getElementById("map_canvas"),{
		zoom: 12,
		center: new google.maps.LatLng(1.3603333, 103.8133333),
		mapTypeId: google.maps.MapTypeId.ROADMAP
	});

	//default capacity 25
	$('#input_capacity').val('25');
	
	//default depot at SoC
	var defaultDepotAddress = 'Singapore 119077';
	var defaultDepotLatLng = new google.maps.LatLng(1.2941205, 103.781059);
	var defaultDepotMarker = new google.maps.Marker({
								position: defaultDepotLatLng,
								title: 'Depot: ' + defaultDepotAddress,
								animation: google.maps.Animation.DROP,
								map: map
							});
	$('#input_depot').val(defaultDepotAddress);
	customersArray.push(new Customer(defaultDepotAddress,0,defaultDepotLatLng,defaultDepotMarker));
	
	$('#button_setdepot').click(function(){
		var address = $('#input_depot').val();
		setDepot(address);
	});
	
	$('#button_add').click(function(){
		var address = $('#input_address').val();
		var demand = parseInt($('#input_demand').val());
		inputCustomer(address, demand);
	});
	
	$('#button_distances').click(function () {
		calcDistances();
	});
	
	$('#button_grasp').click(function () {
		var vehicleCapacity = parseInt($('#input_capacity').val());
		var myGRASP = new GRASP(vehicleCapacity, customersArray, distancesArray);
		myGRASP.exePlanning();
		var toursArray = myGRASP._toursArray;

		for (var t in toursArray) {
			(function(t){
				$('#div_results').append('<p style="font-weight:bold;" class="colororange">Route ' + eval(t+1) + '</p>');
				directionsRenderersArray[t] = [];
				for (var i = 0; i < toursArray[t].length-1; i++) {
					(function(i){
						var directionsRenderer = new google.maps.DirectionsRenderer();
						//directionsRenderer.setMap(map);
						directionsRenderer.setDirections(routesArray[toursArray[t][i]][toursArray[t][i+1]]);
						directionsRenderersArray[t].push(directionsRenderer);
						
						$('#div_results').append(''+
							'From: ' + customersArray[toursArray[t][i]]._address + '<br/>'+
							'To: ' + customersArray[toursArray[t][i+1]]._address + '<br/>'+
							'<span id="button_toggleRenderer' + t + i + '" class="button bgblue">Toggle</span><br/><br/>'
						);
						
						$('#button_toggleRenderer' + t + i).click(function(){
							if (directionsRenderersArray[t][i].getMap()==null) {
								directionsRenderersArray[t][i].setMap(map);
							} else {
								directionsRenderersArray[t][i].setMap(null);
							}
						});
					})(i);
				}
			})(t);
		}
		
	});
	
});


	// google.maps.event.addListener(map,"click",function(event){
		// var marker = new google.maps.Marker({
			// position: event.latLng,
			// title: "HUYHUY3",
			// animation: google.maps.Animation.DROP,
			// map: map
		// });
		// markersArray.push(marker);
	// });
	// google.maps.event.addListener(map, "zoom_changed", function () {
		// var i;
		// for (i=0;i<markersArray.length;i++) {
			// markersArray[i].setMap(null);
		// }
		// markersArray.length = 0;
	// });

